package com.chatplus.application.common.util;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;

public class FieldUtils {

    public static <T> boolean hasModified(T param, T fromDocument, String... ignored) {
        Assert.notEmpty(param, "param can not be null");
        if (fromDocument == null) {
            return true;
        }

        try {
            Field[] declaredFields = param.getClass().getDeclaredFields();
            List<String> ignoredList = null;
            if (ignored != null) {
                ignoredList = Arrays.asList(ignored);
            }
            boolean isEqual = true;
            for (Field field : declaredFields) {
                field.setAccessible(true);

                if (ignoredList != null && ignoredList.contains(field.getName())) {
                    continue;
                }

                if (null == field.get(param) && null == field.get(fromDocument)) {
                    continue;
                }

                if ((null == field.get(param) && null != field.get(fromDocument))
                    || (null != field.get(param) && null == field.get(fromDocument))
                    || !field.get(param).equals(field.get(fromDocument))) {
                    isEqual = false;
                    break;
                }
            }
            return !isEqual;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
